//
//  HTClassHomeVC.swift
//  QuitSmokingApp
//
//  Created by   on 2024/3/6.
//

import UIKit
import Closures

class HTClassHomeVC: HTClassViewController {
    lazy var var_titleLabel: UILabel = {
        let var_label = UILabel()
        var_label.text = "Quit smoking"
        var_label.textColor = .white
        var_label.font = UIFont(name: "RacingSansOne-Regular", size: 28.0)
        return var_label
    }()
    lazy var var_setUp: UIButton = {
        let var_button = UIButton()
        var_button.onTap { [weak self] in
            print("设置")
            self?.navigationController?.pushViewController(HTClassQuitSmokingVC(), animated: true)
        }
        var_button.setImage(UIImage(named: "icon_set_up"), for: .normal)
        return var_button
    }()
    
    lazy var var_search: UIButton = {
        let var_button = UIButton()
        var_button.backgroundColor = .clear
        var_button.onTap { [weak self] in
            self?.navigationController?.pushViewController(HTClassSearchVC(), animated: true)
        }
        return var_button
    }()
    
    lazy var var_search_view: UIView = {
        let var_view = UIView()
        var_view.backgroundColor = .white
        var_view.layer.cornerRadius = 20.auto()
        var_view.layer.masksToBounds = true
        
        
        let var_search_icon = UIImageView()
        var_search_icon.image = UIImage(named: "icon_search")
        var_view.addSubview(var_search_icon)
        var_search_icon.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-4.auto())
            make.centerY.equalToSuperview()
            make.width.height.equalTo(34.auto())
        }
        var_view.addSubview(var_search)
        var_search.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        return var_view
    }()
    
    lazy var var_top_bgView: UIImageView = {
        let var_imageView = UIImageView()
        var_imageView.image = UIImage(named: "icon_top_bg")
        let var_text = UILabel()
        var_text.numberOfLines = 0
        var_text.font = .systemFont(ofSize: 14)
        var_text.text = "Quitting smoking as soon as possible is beneficial for your physical and mental well-being, as well as for your family."
        var_text.textColor = .white
        var_imageView.addSubview(var_text)
        var_text.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15.auto())
            make.width.equalTo(251.auto())
            make.top.equalTo(var_imageView.snp.centerY).offset(10.auto())
        }
        return var_imageView
    }()
    
    lazy var var_bottom_view: UIImageView = {
        let var_imageView = UIImageView()
        var_imageView.image = UIImage(named: "icon_bottom_bg")
        return var_imageView
    }()
    
    lazy var var_bottom_content_view: UIView = {
        let var_view = UIView()
        var_view.backgroundColor = .clear
        var_view.layer.cornerRadius = 8.auto()
        var_view.layer.borderWidth = 1
        var_view.layer.borderColor = UIColor("#298CB2").cgColor
        var_view.layer.shadowColor = UIColor("#298CB2").cgColor
        var_view.layer.shadowOffset = CGSize(width: 15.auto(), height: 15.auto())
        var_view.layer.shadowRadius = 15.auto()
        return var_view
    }()
    
    var var_smokingButton = UIButton()
    
    var today_plan: SmokingCessationPlanModel?
    /// 数量
    lazy var var_smokedLabel: UILabel = {
        let var_label = UILabel()
        var_label.textAlignment = .center
        var_label.font = UIFont(name: "RubikOne-Regular", size: 36)
        return var_label
    }()
    /// 价格
    lazy var var_costLabel: UILabel = {
        let var_label = UILabel()
        var_label.textAlignment = .center
        var_label.font = UIFont(name: "RubikOne-Regular", size: 36)
        return var_label
    }()
    /// 焦油含量
    lazy var var_tarLabel: UILabel = {
        let var_label = UILabel()
        var_label.textAlignment = .center
        var_label.font = UIFont(name: "RubikOne-Regular", size: 36)
        return var_label
    }()
    
    var var_isAlert: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if Array(HTClassStorage.ht_getAllPlan().keys).count == 0 {
            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
                let var_vc = HTClassTool.ht_topVC()
                if var_vc == self &&  !HTClassStorage.ht_getPalnShow() {
                    HTClassStorage.ht_savePalnShow(true)
                    HTClassSetUpView.ht_showAnimated(var_title: "You have not set up my quit smoking plan yet. Click here to set a quit smoking goal") { [weak self] in
                        self?.navigationController?.pushViewController(HTClassQuitSmokingVC(), animated: true)
                    }
                }
            }
        } else {
            // 判断今天是否有计划,没有计划，沿用昨天的计划
            let var_planModel = HTClassStorage.ht_getToDayPlan()
            if var_planModel == nil {
                let var_keys = Array(HTClassStorage.ht_getAllPlan().keys)
                // 将日期字符串转换为日期对象
                let var_dateFormatter = DateFormatter()
                var_dateFormatter.dateFormat = "yyyy-MM-dd"
                let var_sortedDates = var_keys.sorted {
                    guard let var_date1 = var_dateFormatter.date(from: $0),
                          let var_date2 = var_dateFormatter.date(from: $1) else {
                        return false
                    }
                    return var_date1 < var_date2
                }
                let var_key = var_sortedDates.last!
                var var_last_model = HTClassStorage.ht_getAllPlan()[var_key]!
                var_last_model.var_cigarettes_smoked_today = ""
                var_last_model.var_date = HTClassTool.ht_obtainYearMonthDay()
                self.today_plan = var_last_model
                /// 保存计划为今日计划
                HTClassStorage.ht_SaveTodayPlan(var_model: var_last_model)
                ht_ConfigurationData()
            } else {
                self.today_plan = var_planModel
                ht_ConfigurationData()
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
        
        //更新smoking按钮样式
        var_smokingButton.setImage(UIImage(named: "icon_theme_0\(HTClassStorage.ht_getCurrentButton()+1)_button"), for: .normal)
        
        if Array(HTClassStorage.ht_getAllPlan().keys).count > 0 {
            let var_planModel = HTClassStorage.ht_getToDayPlan()
            if var_planModel == nil {
                let var_keys = Array(HTClassStorage.ht_getAllPlan().keys)
                // 将日期字符串转换为日期对象
                let var_dateFormatter = DateFormatter()
                var_dateFormatter.dateFormat = "yyyy-MM-dd"
                let var_sortedDates = var_keys.sorted {
                    guard let var_date1 = var_dateFormatter.date(from: $0),
                          let var_date2 = var_dateFormatter.date(from: $1) else {
                        return false
                    }
                    return var_date1 < var_date2
                }
                let var_key = var_sortedDates.last!
                var var_last_model = HTClassStorage.ht_getAllPlan()["var_key"]!
                var_last_model.var_cigarettes_smoked_today = ""
                self.today_plan = var_last_model
                /// 保存计划为今日计划
                HTClassStorage.ht_SaveTodayPlan(var_model: var_last_model)
                ht_ConfigurationData()
            } else {
                self.today_plan = var_planModel
                ht_ConfigurationData()
            }
        }
    }
    
    override func ht_setUI() {
        super.ht_setUI()
        self.view.addSubview(var_titleLabel)
        var_titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(HTClassTool.STATIC_statusBarHeight + 20.auto())
        }
        self.view.addSubview(var_setUp)
        var_setUp.snp.makeConstraints { make in
            make.centerY.equalTo(var_titleLabel.snp.centerY)
            make.right.equalToSuperview().offset(-15.auto())
        }
        
        self.view.addSubview(var_search_view)
        var_search_view.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15.auto())
            make.right.equalToSuperview().offset(-15.auto())
            make.top.equalTo(var_titleLabel.snp.bottom).offset(20.auto())
            make.height.equalTo(40.auto())
        }
        
        self.view.addSubview(var_top_bgView)
        let var_image = UIImage(named: "icon_top_bg")
        let var_size = var_image!.size
        let var_height = var_size.height/var_size.width * (HTClassTool.STATIC_screenWidth - 30.auto())
        
        var_top_bgView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15.auto())
            make.right.equalToSuperview().offset(-15.auto())
            make.top.equalTo(var_search_view.snp.bottom).offset(20.auto())
            make.height.equalTo(var_height)
        }
        
        
        self.view.addSubview(var_bottom_content_view)
        var_bottom_content_view.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15.auto())
            make.right.equalToSuperview().offset(-15.auto())
            make.top.equalTo(var_top_bgView.snp.bottom).offset(15.auto())
            make.height.equalTo(160.auto())
        }
        
        let var_tag_view_01 = ht_titleTagView(title: "SMOKED\nTODAY")
        let var_tag_view_02 = ht_titleTagView(title: "COST\nTODAY")
        let var_tag_view_03 = ht_titleTagView(title: "TAR\nTODAY")
        let var_lin_01 = UILabel()
        var_lin_01.backgroundColor = UIColor("#4F4F4F")
        var_bottom_content_view.addSubview(var_lin_01)
        let var_lin_02 = UILabel()
        var_lin_02.backgroundColor = UIColor("#4F4F4F")
        var_bottom_content_view.addSubview(var_lin_02)
        
        
        var_bottom_content_view.addSubview(var_costLabel)
        var_bottom_content_view.addSubview(var_tarLabel)
        
        
        let var_item_width = (HTClassTool.STATIC_screenWidth - 30.auto())/3
        
        var_bottom_content_view.addSubview(var_tag_view_01)
        var_tag_view_01.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.width.equalTo(var_item_width)
        }
        var_bottom_content_view.addSubview(var_smokedLabel)
        var_smokedLabel.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalTo(var_tag_view_01.snp.bottom)
            make.bottom.equalTo(var_bottom_content_view.snp.bottom)
            make.width.equalTo(var_item_width)
        }
        
        
        var_lin_01.snp.makeConstraints { make in
            make.left.equalTo(var_tag_view_01.snp.right)
            make.width.equalTo(2)
            make.top.equalToSuperview().offset(15.auto())
            make.bottom.equalToSuperview().offset(-15.auto())
        }
        
        var_bottom_content_view.addSubview(var_tag_view_02)
        var_tag_view_02.snp.makeConstraints { make in
            make.left.equalTo(var_tag_view_01.snp.right)
            make.top.equalToSuperview()
            make.width.equalTo(var_item_width)
        }
        var_bottom_content_view.addSubview(var_costLabel)
        var_costLabel.snp.makeConstraints { make in
            make.left.equalTo(var_tag_view_01.snp.right)
            make.top.equalTo(var_tag_view_02.snp.bottom)
            make.bottom.equalTo(var_bottom_content_view.snp.bottom)
            make.width.equalTo(var_item_width)
        }
        
        
        
        var_lin_02.snp.makeConstraints { make in
            make.left.equalTo(var_tag_view_02.snp.right)
            make.width.equalTo(2)
            make.top.equalToSuperview().offset(15.auto())
            make.bottom.equalToSuperview().offset(-15.auto())
        }
        
        var_bottom_content_view.addSubview(var_tag_view_03)
        var_tag_view_03.snp.makeConstraints { make in
            make.left.equalTo(var_tag_view_02.snp.right)
            make.top.equalToSuperview()
            make.width.equalTo(var_item_width)
        }
        
        var_bottom_content_view.addSubview(var_tarLabel)
        var_tarLabel.snp.makeConstraints { make in
            make.left.equalTo(var_tag_view_02.snp.right)
            make.top.equalTo(var_tag_view_03.snp.bottom)
            make.bottom.equalTo(var_bottom_content_view.snp.bottom)
            make.width.equalTo(var_item_width)
        }
        
        
        let var_button_bg = UIImageView()
        var_button_bg.image = UIImage(named: "icon_theme_01_button_bg")
        self.view.addSubview(var_button_bg)
        var_button_bg.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(var_bottom_content_view.snp.bottom).offset(15.auto())
        }
        
        var_smokingButton.onTap { [weak self] in
            guard let var_model = self?.today_plan else {
                HTClassHudView().ht_showToastOnView(var_view: self!.view, var_title: "Please set a schedule", var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)
                self?.navigationController?.pushViewController(HTClassQuitSmokingVC(), animated: true)
                return
            }
            // 当前的已经吸了多少
            var var_cigarettes_smoked_today = Int(var_model.var_cigarettes_smoked_today) ?? 0
            // 当前限制吸了多少
            let var_dailyCigaretteConsumption = Int(var_model.var_dailyCigaretteConsumption) ?? 0
            if (var_cigarettes_smoked_today >= var_dailyCigaretteConsumption) && !(self?.var_isAlert ?? false) {
                self?.ht_showAlert()
            } else {
                var_cigarettes_smoked_today += 1
                self?.today_plan?.var_cigarettes_smoked_today = "\(var_cigarettes_smoked_today)"
                if let model = self?.today_plan {
                    HTClassStorage.ht_SaveTodayPlan(var_model: model)
                }
                self?.ht_ConfigurationData()
            }
        }
        self.view.addSubview(var_smokingButton)
        var_smokingButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(var_button_bg.snp.centerY)
        }
    }
    
    
    func ht_titleTagView(title: String) -> UIView {
        let var_view = UIView()
        let var_tag = UILabel()
        var_tag.numberOfLines = 2
        var_tag.textAlignment = .center
        var_tag.font = .systemFont(ofSize: 18, weight: .bold)
        var_tag.text = title
        var_tag.textColor = .white
        var_view.addSubview(var_tag)
        var_tag.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(17.auto())
        }
        let var_lin = UIImageView()
        var_lin.image = UIImage(named: "icon_line")
        var_view.addSubview(var_lin)
        var_lin.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(var_tag.snp.bottom).offset(10.auto())
            make.bottom.equalToSuperview()
        }
        return var_view
    }
    
    func ht_ConfigurationData() {
        guard let var_model = self.today_plan else {
            return
        }
        let var_dailyCigaretteConsumption = Int(var_model.var_dailyCigaretteConsumption) ?? 0
        
        let var_cigarettes_smoked_today = Int(var_model.var_cigarettes_smoked_today) ?? 0
        if var_cigarettes_smoked_today == 0 {
            return
        }
        self.var_smokedLabel.text = "\(var_cigarettes_smoked_today)"
        
        let var_total_price = Double(var_cigarettes_smoked_today) * (Double(var_model.var_cigarettePrice) ?? 0.0)
        let var_formattedTotal_price = String(format: "%.1f", var_total_price)
        self.var_costLabel.text = var_formattedTotal_price
        
        let var_total_tar = Double(var_cigarettes_smoked_today) * (Double(var_model.var_tarContentPerCigarette) ?? 0.0)
        let var_formattedTotal_tar = String(format: "%.0f", var_total_tar)
        self.var_tarLabel.text = var_formattedTotal_tar
        
        if var_cigarettes_smoked_today > var_dailyCigaretteConsumption {
            self.var_smokedLabel.textColor = UIColor("#FF1919")
            self.var_costLabel.textColor = UIColor("#FF1919")
            self.var_tarLabel.textColor = UIColor("#FF1919")
        } else {
            self.var_smokedLabel.textColor = UIColor("#FF8719")
            self.var_costLabel.textColor = UIColor("#FF8719")
            self.var_tarLabel.textColor = UIColor("#FF8719")
        }
        self.var_smokedLabel.ht_strokeText()
        self.var_costLabel.ht_strokeText()
        self.var_tarLabel.ht_strokeText()
    }
    func ht_showAlert() {
        // 创建一个 UIAlertController
        let var_alertController = UIAlertController(title: "Warning", message: "You have exceeded the planned number of cigarettes for today. Are you sure you want to continue smoking?", preferredStyle: .alert)
        
        // 添加 Cancel 按钮
        let var_cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
            // 这里可以添加取消按钮的处理逻辑
        }
        var_cancelAction.setValue(UIColor(red: 1.0, green: 0.04, blue: 0.04, alpha: 1.0), forKey: "titleTextColor")
        var_alertController.addAction(var_cancelAction)
        
        // 添加 Continue 按钮
        let var_continueAction = UIAlertAction(title: "Continue", style: .default) { _ in
            guard let var_model = self.today_plan else {
                return
            }
            self.var_isAlert = true
            var var_cigarettes_smoked_today = Int(var_model.var_cigarettes_smoked_today) ?? 0
            var_cigarettes_smoked_today += 1
            self.today_plan?.var_cigarettes_smoked_today = "\(var_cigarettes_smoked_today)"
            if let model = self.today_plan {
                HTClassStorage.ht_SaveTodayPlan(var_model: model)
            }
            self.ht_ConfigurationData()
        }
        var_continueAction.setValue(UIColor(red: 0.15, green: 0.55, blue: 0.77, alpha: 1.0), forKey: "titleTextColor")
        var_alertController.addAction(var_continueAction)
        
        // 显示警告框
        present(var_alertController, animated: true, completion: nil)
    }
}
